<template>
  <div>
    <a-modal
      title="物流信息"
      :confirm-loading="sendModalLoading"
      :mask-closable="false"
      :destroy-on-close="true"
      :visible="visible"
      @ok="send"
      @cancel="$emit('update:visible', false)"
    >
      <a-alert
        v-if="showNotive"
        message="注意"
        description="该订单包含门店自提配送，请确认所有商品都已准备完成再发货！"
        type="error"
      />

      <template v-for="item in transOrderList">
        <div class="content" v-for="(el, inx) in item.goods_info" :key="inx">
          <div class="img">
            <a-avatar shape="square" :size="48" icon="user" :src="el.goods_pic || el.pic" />
          </div>

          <div class="txt">
            <h3>{{ el.name }}</h3>
            <p>
              规格：{{ el.attr_list ? el.attr_list.map((e) => e.attr_name).join() || '默认' : '默认' }} 数量：x{{
                el.num || 0
              }}
            </p>
          </div>
        </div>
      </template>

      <a-tabs :default-active-key="1" v-model="activeKey">
        <a-tab-pane tab="快递" key="1">
          <a-form-item
            >快递公司：
            <a-select style="width: 150px" placeholder="请选择" v-model="express.selectExpress">
              <a-select-option :value="index" v-for="(item, index) of expressList" :key="index">{{
                item
              }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item>
            收件人邮编：<a-input v-model="express.post_code" />
            <a-button @click="print()" size="small">电子面单</a-button>
            <div></div>
            <a href="http://www.c-lodop.com/download.html" target="_blank" class="ts">电子面单打印服务下载地址</a>
          </a-form-item>
          <a-form-item> 快递单号：<a-input v-model="express.express_no" /> </a-form-item>
          <a-form-item>商家留言（选填）：<a-textarea v-model="express.words" /></a-form-item>
        </a-tab-pane>
        <a-tab-pane tab="无需物流" key="0">
          <a-form-item>商家留言（选填）：<a-textarea v-model="express.words" /></a-form-item>
        </a-tab-pane>
      </a-tabs>
    </a-modal>
  </div>
</template>

<script>
import { transOrderStatus } from '@/api/purchase/business'

import {
  modifyPrice,
  getOrderList,
  orderCancel,
  setComments,
  setAddress,
  orderSend,
  orderConfirm,
  orderPrint,
  orderClerk,
  orderPrintMd,
} from '@/api/order'
import { getLodop } from '@/utils/LodopFuncs.js'
export default {
  components: {},
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    expressList: {
      type: Array,
      default: () => [],
    },
    orderId: {
      type: String,
      default: '',
    },
    orderInfo: {
      type: Object,
      default: {},
    },
  },
  data() {
    return {
      activeKey: '1',
      express: {
        words: '',
        express_no: '',
      },
      sendModalLoading: false,
      showNotive: false,

      transOrderList: [],
    }
  },
  computed: {},
  watch: {
    visible(val) {
      if (!val) this.transOrderList = []

      if (val && this.orderInfo?.id) {
        let haveExpress = this.orderInfo.goods_list.some((d) => {
          return d.delivery_type == '0'
        })
        let haveShop = this.orderInfo.goods_list.some((d) => {
          return d.delivery_type == '1'
        })
        // 如果有物流和门店自提订单时，发货时需要提醒该订单包含门店自提
        if (haveExpress && haveShop) {
          this.showNotive = true
        }
      }
    },

    orderId() {
      this.transOrderSupplier(this.orderInfo)
    },
  },
  created() {},
  mounted() {},
  updated() {},
  methods: {
    // 用户点击转单
    transOrderSupplier(row) {
      let goodsList = JSON.parse(JSON.stringify(row.goods_list))

      var map = {},
        dest = []
      goodsList.forEach((item) => {
        if (item.cloud_bind) {
          if (typeof item.cloud_bind !== 'object') {
            item.cloud_bind = JSON.parse(item.cloud_bind)
          }
          var cloud = item.cloud_bind
          if (!map[cloud.cloud_supplier_id]) {
            dest.push({
              province_id: row.province_id,
              city_id: row.city_id,
              district_id: row.district_id,
              address: row.address,
              name: row.name,
              tel: row.mobile,
              cloud_supplier_id: cloud.cloud_supplier_id,
              cloud_supplier_name: cloud.cloud_supplier_name,
              goods_info: [item],
              order_id: row.id,
            })
            map[cloud.cloud_supplier_id] = item
          } else {
            dest.forEach((cloudItem) => {
              if (cloudItem.cloud_supplier_id == item.cloud_bind.cloud_supplier_id) {
                cloudItem.goods_info.push(item)
              }
            })
          }
        }
      })

      // 批量申请转单的价格和状态
      let transStatus = JSON.parse(JSON.stringify(dest))
      let goodsArr = []
      transStatus.forEach((item) => {
        let goods_info = item.goods_info
        goods_info.forEach((good) => {
          let attr = good.attr_list.map((attr) => {
            return attr.attr_id
          })
          goodsArr.push({
            goods_id: good.goods_id + '-' + attr.join('-'),
            attr_id: good.cloud_bind.cloud_attr_id,
            num: good.num,
          })
        })
      })
      if (transStatus.length) {
        let supplier = transStatus[0]
        let statusParam = {
          province_id: supplier.province_id,
          city_id: supplier.city_id,
          district_id: supplier.district_id,
          address: supplier.address,
          name: supplier.name,
          tel: supplier.tel,
          goods_info: goodsArr,
          order_id: supplier.order_id,
        }

        this.transOrderStatus(statusParam, dest)
      }

      return
    },

    // 查询转单的价格和状态
    async transOrderStatus(params, arr) {
      params.goods_info = JSON.stringify(params.goods_info)
      const res = await transOrderStatus(params)
      if (res.code == 0) {
        console.log(res)
        let supplierArr = res.data
        arr.forEach((item) => {
          supplierArr.forEach((supplier) => {
            if (item.cloud_supplier_id == supplier.supplier.id) {
              item.express_price = supplier.express_price
              item.pay_price = supplier.pay_price
              item.cloud_order_status = supplier.cloud_order_status
            }
          })
        })
        this.transOrderList = arr
      }
    },

    send() {
      const hide = this.$message.loading('发货中...', 0)
      var params = {
        order_id: this.orderId,
        words: this.express.words,
      }
      if (this.activeKey === '1') {
        params.is_express = 1
        params.express = this.expressList[this.express.selectExpress]
        params.post_code = this.express.post_code
        params.express_no = this.express.express_no
      } else {
        params.is_express = 0
      }
      orderSend(params).then((res) => {
        hide()
        if (res.code === 0) {
          this.express = {
            words: '',
            express_no: '',
            selectExpress: '',
          }
          this.$message.success('发货成功！')
          this.$emit('update:visible', false)
          this.$emit('onAfterClose')
        } else {
          this.$error({
            content: res.msg,
          })
        }
      })
    },
    // 打印电子面单
    print() {
      let LODOP = getLodop()
      console.log('LODOP,', LODOP)
      if (!LODOP) {
        this.$error({
          content: '请运行或者下载打印插件',
        })
        return
      }
      if (this.expressList[this.express.selectExpress]) {
        const hide = this.$message.loading('打印中...', 0)
        orderPrintMd({
          id: this.orderId,
          express: this.expressList[this.express.selectExpress],
          code: this.express.post_code,
        }).then((res) => {
          hide()
          if (res.code == 0) {
            this.express.express_no = res.data.Order.LogisticCode
            LODOP.PRINT_INIT('')
            LODOP.ADD_PRINT_HTM(10, 50, '100%', '100%', res.data.PrintTemplate)
            LODOP.PRINT_DESIGN()
            this.$message.success('打印成功')
            return
          } else {
            this.$error({
              content: res.msg,
            })
          }
        })
      } else {
        this.$error({
          content: '请选择快递',
        })
      }
    },
  },
}
</script>

<style scoped lang="less">
.content {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  height: 48px;
  overflow: hidden;

  .txt {
    margin-left: 16px;
    flex: 1;
    overflow: hidden;

    * {
      margin: 0;
      font-size: 14px;
      text-overflow: ellipsis;
      white-space: nowrap;
      overflow: hidden;
    }

    h3 {
      color: rgba(0, 0, 0, 0.85);
    }

    p {
      color: rgba(0, 0, 0, 0.45);
    }
  }
}
</style>
